using DeviceCommons.DeviceMessages.Builders;
using DeviceCommons.DeviceMessages.Factories;
using DeviceCommons.DeviceMessages.Enums;

namespace ConsoleTestApp
{
    /// <summary>
    /// 设备状态配置演示程序
    /// 展示如何使用新的设备状态配置系统
    /// </summary>
    public class DeviceStateConfigurationDemo
    {
        public static void RunDemo()
        {
            Console.WriteLine("=== 设备状态配置系统演示 ===\n");

            // 1. 注册设备类型1的状态配置（使用专门的数值类型方法）
            Console.WriteLine("1. 注册设备类型1的状态配置（使用专门的数值类型方法）...");
            DeviceStateConfigurationRegistry.RegisterConfiguration(1, builder =>
            {
                builder
                    .AddStringState(1, "设备名称", "设备的显示名称", true, "默认设备")
                    .AddInt32State(2, "温度", "设备温度值", true, 25, value => 
                    {
                        if (value is int temp)
                            return temp >= -50 && temp <= 150;
                        return false;
                    })
                    .AddBooleanState(3, "运行状态", "设备是否正在运行", true, false);
            });

            // 2. 注册设备类型2的状态配置（使用Float32类型）
            Console.WriteLine("2. 注册设备类型2的状态配置（使用Float32类型）...");
            DeviceStateConfigurationRegistry.RegisterConfiguration(2, builder =>
            {
                builder
                    .AddFloat32State(1, "电压", "设备电压值", true, 220.0f, value =>
                    {
                        if (value is float voltage)
                            return voltage >= 0 && voltage <= 500;
                        return false;
                    })
                    .AddStringState(2, "位置", "设备位置信息", false, "未知位置");
            });

            // 3. 注册设备类型3的状态配置（使用通用AddNumericState重载方法）
            Console.WriteLine("3. 注册设备类型3的状态配置（使用通用AddNumericState重载方法）...");
            DeviceStateConfigurationRegistry.RegisterConfiguration(3, builder =>
            {
                builder
                    .AddStringState(1, "传感器名称", "传感器标识名称", true, "默认传感器")
                    .AddNumericState(2, StateValueTypeEnum.Int16, "压力", "压力传感器值", true, (short)100, value =>
                    {
                        if (value is short pressure)
                            return pressure >= 0 && pressure <= 1000;
                        return false;
                    })
                    .AddNumericState(3, StateValueTypeEnum.UInt16, "流量", "流量计数值", true, (ushort)50, value =>
                    {
                        if (value is ushort flow)
                            return flow >= 0 && flow <= 1000;
                        return false;
                    })
                    .AddTimestampState(4, "时间戳", "数据采集时间", true, (ulong)DateTimeOffset.UtcNow.ToUnixTimeSeconds());
            });

            // 4. 显示注册的配置信息
            Console.WriteLine("4. 显示注册的配置信息...");
            var (totalDeviceTypes, totalStates) = DeviceStateConfigurationRegistry.GetStatistics();
            Console.WriteLine($"已注册设备类型数量: {totalDeviceTypes}");
            Console.WriteLine($"总状态数量: {totalStates}\n");

            foreach (var deviceType in DeviceStateConfigurationRegistry.GetRegisteredDeviceTypes())
            {
                var config = DeviceStateConfigurationRegistry.GetConfiguration(deviceType);
                if (config != null)
                {
                    Console.WriteLine($"设备类型 {deviceType}:");
                    foreach (var stateDef in config.StateDefinitions)
                    {
                        var required = stateDef.IsRequired ? "必需" : "可选";
                        var defaultValue = stateDef.DefaultValue?.ToString() ?? "无";
                        Console.WriteLine($"  状态 {stateDef.Sid}: {stateDef.Name} ({stateDef.Description}) - {stateDef.ValueType} - {required} - 默认值: {defaultValue}");
                    }
                    Console.WriteLine();
                }
            }

            // 5. 使用增强的构建器创建设备消息
            Console.WriteLine("5. 使用增强的构建器创建设备消息...");
            
            // 创建设备类型1的消息（Int32温度值）
            Console.WriteLine("创建设备类型1的消息（Int32温度值）:");
            var builder1 = new EnhancedDeviceMessageBuilder();
            var message1 = builder1
                .WithMainDevice("DEV001", 1)
                .AddReadingWithConfiguration(0, 
                    (1, "温度传感器A"),
                    (2, 28),  // Int32类型
                    (3, true))
                .Build();

            Console.WriteLine($"设备类型1消息创建成功，包含 {message1.MainDevice.Reading.ReadingArray.Length} 个读数");
            Console.WriteLine($"第一个读数包含 {message1.MainDevice.Reading.ReadingArray[0].State.StateArray.Length} 个状态\n");

            // 创建设备类型2的消息（Float32电压值）
            Console.WriteLine("创建设备类型2的消息（Float32电压值）:");
            var builder2 = new EnhancedDeviceMessageBuilder();
            var message2 = builder2
                .WithMainDevice("DEV002", 2)
                .AddReadingWithConfiguration(0, 
                    (1, 230.5f),  // Float32类型
                    (2, "车间A"))
                .Build();

            Console.WriteLine($"设备类型2消息创建成功，包含 {message2.MainDevice.Reading.ReadingArray.Length} 个读数");
            Console.WriteLine($"第一个读数包含 {message2.MainDevice.Reading.ReadingArray[0].State.StateArray.Length} 个状态\n");

            // 创建设备类型3的消息（混合数值类型）
            Console.WriteLine("创建设备类型3的消息（混合数值类型）:");
            var builder3 = new EnhancedDeviceMessageBuilder();
            var message3 = builder3
                .WithMainDevice("DEV003", 3)
                .AddReadingWithConfiguration(0, 
                    (1, "压力传感器B"),
                    (2, (short)150),  // Int16类型
                    (3, (ushort)75),  // UInt16类型
                    (4, (ulong)DateTimeOffset.UtcNow.ToUnixTimeSeconds()))  // Timestamp类型
                .Build();

            Console.WriteLine($"设备类型3消息创建成功，包含 {message3.MainDevice.Reading.ReadingArray.Length} 个读数");
            Console.WriteLine($"第一个读数包含 {message3.MainDevice.Reading.ReadingArray[0].State.StateArray.Length} 个状态\n");

            // 6. 演示自动填充默认值
            Console.WriteLine("6. 演示自动填充默认值...");
            var builder4 = new EnhancedDeviceMessageBuilder();
            var message4 = builder4
                .WithMainDevice("DEV004", 1)
                .AddReadingWithDefaults(0, 
                    (2, 30)) // 只提供温度值，其他使用默认值
                .Build();

            var states = message4.MainDevice.Reading.ReadingArray[0].State.StateArray;
            Console.WriteLine("自动填充默认值后的状态:");
            foreach (var state in states)
            {
                Console.WriteLine($"  状态 {state.SID}: {state.ValueText} ({state.ValueType})");
            }
            Console.WriteLine();

            // 7. 演示验证功能
            Console.WriteLine("7. 演示验证功能...");
            try
            {
                var builder5 = new EnhancedDeviceMessageBuilder();
                var message5 = builder5
                    .WithMainDevice("DEV005", 1)
                    .AddReadingWithConfiguration(0, 
                        (1, "测试设备")) // 缺少必需的状态2和3
                    .Build();
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine($"验证失败: {ex.Message}");
            }

            // 8. 演示自定义验证规则
            Console.WriteLine("\n8. 演示自定义验证规则...");
            try
            {
                var builder6 = new EnhancedDeviceMessageBuilder();
                var message6 = builder6
                    .WithMainDevice("DEV006", 1)
                    .AddReadingWithConfiguration(0, 
                        (1, "测试设备"),
                        (2, 200), // 温度超出范围（-50到150）
                        (3, true))
                    .Build();
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine($"验证规则检查失败: {ex.Message}");
            }

            Console.WriteLine("\n=== 演示完成 ===");
        }

        /// <summary>
        /// 演示批量注册设备配置
        /// </summary>
        public static void RunBatchRegistrationDemo()
        {
            Console.WriteLine("\n=== 批量注册设备配置演示 ===\n");

            // 批量注册多个设备类型（使用新的专门数值类型方法）
            var configurations = new[]
            {
                DeviceStateConfigurationBuilder.Create((byte)10)
                    .AddStringState(1, "传感器类型")
                    .AddInt32State(2, "测量值")
                    .Build(),
                
                DeviceStateConfigurationBuilder.Create((byte)11)
                    .AddBooleanState(1, "开关状态")
                    .AddFloat32State(2, "电流值")
                    .AddStringState(3, "设备描述", null, false, null)
                    .Build(),
                
                DeviceStateConfigurationBuilder.Create((byte)12)
                    .AddInt16State(1, "压力值")
                    .AddUInt16State(2, "流量值")
                    .AddBooleanState(3, "报警状态")
                    .AddStringState(4, "备注", null, false, null)
                    .Build(),

                DeviceStateConfigurationBuilder.Create((byte)13)
                    .AddStringState(1, "设备标识")
                    .AddNumericState(2, StateValueTypeEnum.Double, "精度值", "高精度测量值", true, 0.001)
                    .AddTimestampState(3, "采集时间", "数据采集时间戳", true, (ulong)DateTimeOffset.UtcNow.ToUnixTimeSeconds())
                    .Build()
            };

            DeviceStateConfigurationRegistry.RegisterConfigurations(configurations);

            Console.WriteLine("批量注册完成！");
            var (totalDeviceTypes, totalStates) = DeviceStateConfigurationRegistry.GetStatistics();
            Console.WriteLine($"当前已注册设备类型数量: {totalDeviceTypes}");
            Console.WriteLine($"总状态数量: {totalStates}");

            // 显示新注册的设备类型
            Console.WriteLine("\n新注册的设备类型:");
            foreach (var deviceType in new[] { (byte)10, (byte)11, (byte)12, (byte)13 })
            {
                var config = DeviceStateConfigurationRegistry.GetConfiguration(deviceType);
                if (config != null)
                {
                    Console.WriteLine($"设备类型 {deviceType}: {config.StateDefinitions.Count} 个状态");
                    foreach (var stateDef in config.StateDefinitions)
                    {
                        Console.WriteLine($"  状态 {stateDef.Sid}: {stateDef.Name} - {stateDef.ValueType}");
                    }
                }
            }
        }
    }
}
